import 'dart:collection';

import 'package:get/get.dart';
import 'package:kkhousekeep/models/member.dart';
import 'package:kkhousekeep/net/me_member_connect.dart';
import 'package:kkhousekeep/page/login/login_controller.dart';
import 'package:kkhousekeep/tools/shared_preferences.dart';

import '../../models/member_list_entity.dart';

class FamilyMemberController extends GetxController {
  var memberList = <MemberListObjList>[].obs;
  var item = <Object>[].obs;
  late MeMemberConnect meMemberConnect;
  late UserType userType;

  @override
  void onInit() {
    /// 用户登陆就调用了MeMemberConnect获取头像
    meMemberConnect = Get.isRegistered<MeMemberConnect>()
        ? Get.find<MeMemberConnect>()
        : Get.put(MeMemberConnect());
    super.onInit();
    _loadNetworkData();
  }

  void _loadNetworkData() async {
    userType = await getSp().getUserType();
    loadMemberList();
  }

  Future<void> loadMemberList() async {
    item.clear();
    memberList.value = await meMemberConnect.getMemberList();
    Map<String?, List<MemberListObjList>> relationshipMapMembers =
        groupBy(memberList, (member) => member.relationship);
    relationshipMapMembers.forEach((key, value) {
      if (key == MemberRelationship.owner.value) {
        item.add(MemberRelationship.owner.description);
        item.addAll(value);
      } else if (key == MemberRelationship.familyMember.value &&
          userType != UserType.tenant) {
        item.add(MemberRelationship.familyMember.description);
        item.addAll(value);
      } else if (key == MemberRelationship.tenant.value) {
        item.add(MemberRelationship.tenant.description);
        item.addAll(value);
      }
    });
  }

  Map<T, List<S>> groupBy<S, T>(Iterable<S> values, T Function(S) key) {
    var map = <T, List<S>>{};
    for (var element in values) {
      (map[key(element)] ??= []).add(element);
    }
    return SplayTreeMap.from(map);
  }
}
